package com.smh.aiagent.advisers;

import org.springframework.ai.chat.client.advisor.api.*;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.Map;

public class ReReadingAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {


    private AdvisedRequest before(AdvisedRequest advisedRequest) {

        Map<String, Object> advisedUserParams = new HashMap<>(advisedRequest.userParams());
        String userText = advisedRequest.userText();
        advisedUserParams.put("re2_input_query", userText);

//		advisedRequest = advisedRequest.updateContext(context -> {
//			context.put("userText", userText);
//			return context;
//		}); // 添加一个上下文参数，方便后续使用, 这个方法会创建新的请求对象和新的context,保证不会改变原始请求对象
//
//		Object o = advisedRequest.adviseContext().get(userText);// 可以实现不同拦截器之间的数据传递,相当于一次请求的全局变量

        return AdvisedRequest.from(advisedRequest)
                .userText("""
                        {re2_input_query}
                        Read the question again: {re2_input_query}
                        """)
                .userParams(advisedUserParams)
                .build();

        // 就是让AI读两遍
    }

    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        return chain.nextAroundCall(this.before(advisedRequest));
    }

    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        return chain.nextAroundStream(this.before(advisedRequest));
    }

    @Override
    public int getOrder() {
        return 1;
    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }
}